#!/bin/bash

# 微信公众号排版工具 - 服务器一键部署脚本
# 使用方法: bash deploy-to-server.sh

set -e

echo "╔════════════════════════════════════════════════════════╗"
echo "║     微信公众号排版工具 - 服务器部署脚本               ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 配置变量
PROJECT_DIR="/var/www/wechat-format-tool"
BACKEND_DIR="$PROJECT_DIR/backend"
FRONTEND_DIR="$PROJECT_DIR/frontend"
NGINX_CONFIG="/etc/nginx/sites-available/wechat-format-tool"

# 函数：打印成功信息
success() {
    echo -e "${GREEN}✓ $1${NC}"
}

# 函数：打印错误信息
error() {
    echo -e "${RED}✗ $1${NC}"
}

# 函数：打印警告信息
warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

# 函数：检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        error "$1 未安装"
        return 1
    else
        success "$1 已安装"
        return 0
    fi
}

# 步骤1: 检查环境
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "步骤 1/7: 检查环境"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

check_command node || exit 1
check_command npm || exit 1
check_command nginx || exit 1
check_command pm2 || exit 1
check_command git || exit 1

echo ""

# 步骤2: 创建项目目录
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "步骤 2/7: 创建项目目录"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ ! -d "$PROJECT_DIR" ]; then
    sudo mkdir -p $PROJECT_DIR
    sudo chown -R $USER:$USER $PROJECT_DIR
    success "项目目录创建成功: $PROJECT_DIR"
else
    warning "项目目录已存在: $PROJECT_DIR"
fi

echo ""

# 步骤3: 复制项目文件
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "步骤 3/7: 部署项目文件"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ "$(pwd)" != "$PROJECT_DIR" ]; then
    warning "请手动将项目文件复制到服务器"
    echo "方法1: 使用 scp"
    echo "  scp -r ./wechat-format-tool user@your-server:$PROJECT_DIR"
    echo ""
    echo "方法2: 使用 git clone"
    echo "  cd $PROJECT_DIR"
    echo "  git clone <your-repo-url> ."
    echo ""
    read -p "文件已复制？按 Enter 继续..."
fi

cd $PROJECT_DIR
success "切换到项目目录"

echo ""

# 步骤4: 部署后端
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "步骤 4/7: 部署后端"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

cd $BACKEND_DIR

# 检查 .env 文件
if [ ! -f .env ]; then
    warning ".env 文件不存在，正在创建..."
    cat > .env << EOF
# 服务器配置
PORT=3000
NODE_ENV=production
CORS_ORIGIN=http://localhost

# 数据库配置
DB_HOST=122.51.186.204
DB_PORT=3306
DB_NAME=wechat_format
DB_USER=dev_user
DB_PASSWORD=Admin@9000

# Redis配置
REDIS_HOST=122.51.186.204
REDIS_PORT=6379
REDIS_PASSWORD=Admin@9000

# JWT配置
JWT_SECRET=$(openssl rand -base64 32)
JWT_EXPIRE=7d

# 文件上传配置
UPLOAD_PATH=./uploads
MAX_FILE_SIZE=10485760
EOF
    success ".env 文件创建成功"
    warning "请修改 .env 文件中的配置（特别是 CORS_ORIGIN）"
    read -p "按 Enter 继续..."
fi

# 安装依赖
echo "正在安装后端依赖..."
npm install --production
success "后端依赖安装完成"

# 创建上传目录
mkdir -p uploads logs
chmod 755 uploads
success "创建上传目录和日志目录"

# 创建 PM2 配置文件
if [ ! -f ecosystem.config.js ]; then
    cat > ecosystem.config.js << 'EOF'
module.exports = {
  apps: [{
    name: 'wechat-format-backend',
    script: './src/app.js',
    instances: 2,
    exec_mode: 'cluster',
    watch: false,
    max_memory_restart: '500M',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    },
    error_file: './logs/error.log',
    out_file: './logs/out.log',
    log_date_format: 'YYYY-MM-DD HH:mm:ss',
    merge_logs: true,
    autorestart: true,
    max_restarts: 10,
    min_uptime: '10s'
  }]
}
EOF
    success "PM2 配置文件创建成功"
fi

# 启动后端
echo "正在启动后端服务..."
pm2 delete wechat-format-backend 2>/dev/null || true
pm2 start ecosystem.config.js
pm2 save
success "后端服务启动成功"

echo ""

# 步骤5: 构建前端
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "步骤 5/7: 构建前端"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

cd $FRONTEND_DIR

# 创建生产环境配置
if [ ! -f .env.production ]; then
    echo "VITE_API_URL=/api" > .env.production
    success ".env.production 创建成功"
fi

# 安装依赖
echo "正在安装前端依赖..."
npm install
success "前端依赖安装完成"

# 构建
echo "正在构建前端..."
npm run build
success "前端构建完成"

echo ""

# 步骤6: 配置Nginx
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "步骤 6/7: 配置Nginx"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ ! -f $NGINX_CONFIG ]; then
    sudo bash -c "cat > $NGINX_CONFIG" << EOF
server {
    listen 80;
    server_name _;
    
    # 前端静态文件
    location / {
        root $FRONTEND_DIR/dist;
        try_files \$uri \$uri/ /index.html;
        index index.html;
    }
    
    # 后端API代理
    location /api {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
        client_max_body_size 10M;
    }
    
    # 图片访问
    location /uploads {
        alias $BACKEND_DIR/uploads;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript 
               application/x-javascript application/xml+rss 
               application/javascript application/json;
}
EOF
    success "Nginx 配置文件创建成功"
    
    # 启用配置
    sudo ln -sf $NGINX_CONFIG /etc/nginx/sites-enabled/wechat-format-tool
    success "Nginx 配置已启用"
else
    warning "Nginx 配置文件已存在"
fi

# 测试Nginx配置
sudo nginx -t
if [ $? -eq 0 ]; then
    success "Nginx 配置测试通过"
    sudo systemctl reload nginx
    success "Nginx 重新加载完成"
else
    error "Nginx 配置测试失败"
    exit 1
fi

echo ""

# 步骤7: 设置开机自启
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "步骤 7/7: 设置开机自启"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# PM2 开机自启
pm2 startup systemd -u $USER --hp $HOME 2>/dev/null || true
pm2 save
success "PM2 开机自启设置完成"

# Nginx 开机自启
sudo systemctl enable nginx
success "Nginx 开机自启设置完成"

echo ""

# 完成
echo "╔════════════════════════════════════════════════════════╗"
echo "║                   部署完成！ 🎉                        ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""
echo "访问地址:"
echo "  HTTP:  http://$(hostname -I | awk '{print $1}')"
echo "  本地:  http://localhost"
echo ""
echo "管理命令:"
echo "  查看后端状态:    pm2 status"
echo "  查看后端日志:    pm2 logs wechat-format-backend"
echo "  重启后端:        pm2 restart wechat-format-backend"
echo "  重启Nginx:       sudo systemctl restart nginx"
echo ""
echo "后续步骤:"
echo "  1. 配置域名解析到服务器IP"
echo "  2. 修改 $BACKEND_DIR/.env 中的 CORS_ORIGIN"
echo "  3. 安装SSL证书（推荐使用 Let's Encrypt）"
echo "  4. 配置防火墙（开放80和443端口）"
echo ""
echo "查看详细文档: ./Linux服务器部署指南.md"
echo ""

